// Copyright©,2020-2025
// Author: caocheng
// Version: 1.0.0
// Date: 2021/3/9 17:06
// Description：
package filter

import (
	SummerLogger "gitee.com/chrischo/go-summer/summer/summer-logger"
	SummerWeb "gitee.com/chrischo/go-summer/summer/summer-web"
	"net/http"
)

type ApiFilter struct {
}

func (f *ApiFilter) Invoke(ctx SummerWeb.WebContext, chain SummerWeb.FilterChain) {
	f.cors(ctx)
	SummerLogger.Info("1111111111111")
	chain.Next(ctx)
}

// 处理跨域请求,支持options访问
func (f *ApiFilter) cors(ctx SummerWeb.WebContext) {
	method := ctx.Request().Method
	origin := ctx.Request().Header.Get("Origin")
	ctx.Header("Access-Control-Allow-Origin", origin)
	ctx.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token,X-Token,X-User-Id")
	ctx.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS,DELETE,PUT")
	ctx.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
	ctx.Header("Access-Control-Allow-Credentials", "true")

	// 放行所有OPTIONS方法
	if method == "OPTIONS" {
		ctx.ResponseWriter().WriteHeader(http.StatusNoContent)
		ctx.Abort()
	}
}
